const app = getApp()
const db = wx.cloud.database()
Page({

  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    navIndex: 0,
    classList: ['全部', '数码电子', '二手书籍', '生活用品', '服装配饰', '其他'],
    percentageList: ['几乎全新', '9成新', '8成新', '6成新', '比较旧'],
    goodsList: [],
    authorizeModal: false
  },

  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    })
    db.collection('secondhand').orderBy('createTime', 'desc').get().then(res => {
      console.log(res)
      this.setData({
        goodsList: res.data
      })
      wx.hideLoading()
    }).catch(err => {
      console.log(err)
    })
  },

  onReady: function () {

  },

  onShow: function () {

  },

  onHide: function () {

  },

  onUnload: function () {

  },

  onPullDownRefresh: function () {

  },

  onReachBottom: function () {

  },

  onShareAppMessage: function () {

  },

  // 根据二手的分类class获取对应分类下商品，-1表示所有
  getSecondHandDataByType(type){
    return db.collection('secondhand').where({
      class: type === -1 ? undefined : type
    }).orderBy('createTime','desc').get()
  },

  // 切换tab，获取对应分类
  async tabSelect(e) {
    let navIndex = parseInt(e.currentTarget.dataset.id) - 1
    try{
      wx.showLoading({
        title: '加载中',
      })
      let res = await this.getSecondHandDataByType(navIndex)
      this.setData({
        navIndex: navIndex + 1,
        scrollLeft: navIndex * 60,
        goodsList: res.data
      })
      wx.hideLoading()
    } catch(e){
      wx.showToast({
        title: '啊哦，出错了',
      })
    }
  },

  // 跳转发布页
  onPublishSecondHand() {
    let userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      this.setData({
        authorizeModal: true
      })
      return
    }

    wx.navigateTo({
      url: '/pages/publish-items/secondhand/secondhand',
    })
  },

  // 去二手详情页
  navigateToDetail(e) {
    let goodId = e.currentTarget.dataset.goodid
    wx.navigateTo({
      url:  `/pages/publish-lists/secondhand/detail/detail?goodId=${goodId}`,
    })
  },


    // 用户授权
    authorizeLogin(e) {
      console.log('e.detail.userInfo', e.detail.userInfo)
      if (e.detail.userInfo) {
        this.setData({
          authorizeModal: false
        })
        wx.setStorageSync('userInfo', e.detail.userInfo)
        app.globalData.userInfo = e.detail.userInfo
        this.addUser(app.globalData.userInfo)
      }
    },
  
    // 如果数据库没有此用户，则添加
    async addUser(user) {
      try {
        // 检查数据库是否有了
        let res = await db.collection('user').where({
          _openid: wx.getStorageSync('openid')
        }).get()
        if (res.data.length === 0) {
          console.log('该用户为新用户')
          // 没有的话添加
          await db.collection('user').add({
            data: user
          })
          wx.showToast({
            title: '登陆成功',
          })
        } else {
          await db.collection('user').where({
            _openid: wx.getStorageSync('openid')
          }).update({
            data: user
          })
        }
      } catch (e) {
        wx.showToast({
          title: '啊哦，出错了',
        })
      }
    },

    hideAuthorizeModal() {
      this.setData({
        authorizeModal: false
      })
    }
})